﻿<div id="app" class="common-layout">
    <!-- 销售订单基础信息 -->
    <div class="basicInfo">
        <h4 class="titleH">基础信息</h4>
        <hr />
        <div class="form-container">
            <el-form :model="form" label-width="120px" class="basicInfoForm">
                <table class="orderTable">
                    <tbody>
                        <!-- 第一行：销售单号 + 销售日期 -->
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;销售单号
                            </td>
                            <td>
                                <el-input v-model="form.salesOrderNo"
                                          placeholder="自动获取系统编号"
                                          style="width:70%"
                                          readonly />
                            </td>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;销售日期
                            </td>
                            <td>
                                <el-date-picker v-model="form.salesDate"
                                                type="date"
                                                format="YYYY/MM/DD"
                                                value-format="YYYY/MM/DD"
                                                placeholder="选择销售日期"
                                                :default-value="new Date()"
                                                style="width: 160px;" />
                            </td>
                        </tr>

                        <!-- 第二行：客户名称 + 联系方式 -->
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;客户名称
                            </td>
                            <td>
                                <el-select v-model="form.customerId"
                                           placeholder="请选择客户"
                                           style="width:70%"
                                           v-on:change="handleCustomerChange">
                                    <el-option v-for="item in customerOptions"
                                               :key="item.id"
                                               :label="item.name"
                                               :value="item.id" />
                                </el-select>
                            </td>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;联系方式
                            </td>
                            <td>
                                <el-input v-model="form.customerPhone"
                                          placeholder="客户联系方式"
                                          style="width:70%"
                                          readonly />
                            </td>
                        </tr>

                        <!-- 第三行：联系人 + 销售部门 -->
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;联系人
                            </td>
                            <td>
                                <el-input v-model="form.customerContact"
                                          placeholder="客户联系人"
                                          style="width:70%"
                                          readonly />
                            </td>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;销售部门
                            </td>
                            <td>
                                <el-input placeholder="请选择"
                                          v-model="selectedDepart"
                                          style="width:70%"
                                          readonly
                                          v-on:click="salesDepartVisible = true"></el-input>
                            </td>
                        </tr>

                        <!-- 第四行：销售负责人 -->
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;销售负责人
                            </td>
                            <td>
                                <el-input placeholder="请选择"
                                          v-model="selectedManName"
                                          style="width:70%"
                                          readonly
                                          v-on:click="openManModal"></el-input>
                            </td>
                            <td></td>
                            <td></td>
                        </tr>

                        <!-- 第五行：备注 -->
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;备注
                            </td>
                            <td colspan="3">
                                <el-input v-model="form.remarks"
                                          type="textarea"
                                          placeholder="请输入备注信息"
                                          style="width:100%" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </el-form>
        </div>
    </div>

    <!-- 销售货品明细 -->
    <div class="stockInfo">
        <h4 class="titleH">销售货品明细</h4>
        <hr />
        <div class="add-remove-buttons">
            <el-button type="success" v-on:click="openGoodsSelectModal">添加</el-button>
            <el-button type="danger" v-on:click="removeSelectedDetails">移除选中</el-button>
        </div>
        <div class="stockTable">
            <el-table :data="salesDetails" style="width: 100%" v-on:selection-change="handleDetailSelection"
                      ref="detailTable" stripe border>
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="序号" width="80">
                    <template #default="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column prop="goodsName" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="goodsCode" label="货品编号" width="150"></el-table-column>
                <el-table-column prop="specification" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="unit" label="单位" width="100">
                    <template #default="scope">
                        <el-select v-model="scope.row.unit" placeholder="请选择" style="width: 100%">
                            <el-option label="个" value="个"></el-option>
                            <el-option label="瓶" value="瓶"></el-option>
                            <el-option label="kg" value="kg"></el-option>
                            <el-option label="ml" value="ml"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="goodsType" label="货品类型" width="120"></el-table-column>
                <el-table-column prop="currentStock" label="当前库存" width="120" align="right">
                    <template #default="scope">
                        <span :class="{'stock-warning': scope.row.currentStock < 10, 'stock-error': scope.row.currentStock === 0}">
                            {{ scope.row.currentStock }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="orderQuantity" label="货品数量" width="180">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.orderQuantity"
                                  placeholder="请输入"
                                  v-on:input="handleQuantityInput(scope.row, $event)"
                                  v-on:blur="validateQuantity(scope.row)"
                                  min="1"
                                  :max="scope.row.currentStock" />
                        <div v-if="scope.row.currentStock > 0" class="quantity-input-hint">
                            最大可输入: {{ scope.row.currentStock }}
                        </div>
                        <div v-else class="quantity-input-error">
                            库存不足，无法销售
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="salesUnitPrice" label="销售单价" width="120">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.salesUnitPrice" placeholder="请输入"
                                  v-on:change="calculateAmount(scope.row)" min="0.01" step="0.01" />
                    </template>
                </el-table-column>
                <el-table-column prop="salesAmount" label="销售金额" width="140" align="right">
                    <template #default="scope">{{ formatNumber(scope.row.salesAmount) }}</template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" width="150">
                    <template #default="scope">
                        <el-input v-model="scope.row.remarks" placeholder="请输入" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button link type="danger" size="small" v-on:click="removeDetail(scope.row)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="total-summary">
            合计：货品数量 {{ totalQuantity }} 件，销售金额 {{ formatNumber(totalAmount) }} 元
        </div>
    </div>

    <!-- 附件上传区域 -->
    <div class="uploadAttachment">
        <h4 class="titleH">上传附件</h4>
        <hr />
        <div class="uploadAttach">
            <div class="uploadBtn">
                <input type="file"
                       ref="fileInput"
                       v-on:change="handleFileUpload"
                       accept=".doc,.docx,.pdf,.rar,.zip"
                       multiple
                       style="display: none" />
                <el-button type="primary" v-on:click="triggerFileInput">上传附件</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span class="promptWord">您可以上传doc、pdf、rar、zip等格式的文件，单个文件最大200MB</span>
            </div>
            <div class="attachment-list">
                <div v-for="(file, index) in uploadedFiles" :key="index" class="attachment-item">
                    <div class="attachment-info">
                        <el-icon class="attachment-icon">
                            <document />
                        </el-icon>
                        <span>{{ file.name }}</span>
                    </div>
                    <div class="attachment-actions">
                        <el-button size="small"
                                   type="text"
                                   style="color: #ff4d4f;"
                                   v-on:click="removeFile(index)">
                            删除
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 底部保存栏 -->
    <div class="saveBlock">
        <div class="btnBlock">
            <el-button v-on:click="closePage">关闭</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;<el-button v-on:click="saveDraft">保存草稿</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;<el-button v-on:click="saveAndAdd">保存并新增</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;<el-button type="success" v-on:click="submitForm">提交订单</el-button>
        </div>
    </div>

    <!-- 销售部门选择模态框 -->
    <el-dialog v-model="salesDepartVisible" :modal="false" style="width:400px">
        <h3>选择销售部门</h3>
        <hr />
        <br />
        <el-input v-model="departSearchKey"
                  placeholder="请输入部门名称搜索"
                  class="search-input"
                  clearable>
            <template #prefix>
                <el-icon class="el-input__icon"><Search /></el-icon>
            </template>
        </el-input>
        <br />
        <br />
        <div class="tree-container">
            <el-tree style="max-width: 300px"
                     :data="filteredDepartData"
                     :props="defaultProps"
                     :expand-on-click-node="false"
                     :default-expanded-keys="[1]"
                     v-on:node-click="departNode" />
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="salesDepartVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="confirmDepart">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 销售负责人选择模态框 -->
    <el-dialog v-model="salesManVisible" :modal="false" style="width:400px">
        <h3>选择销售负责人</h3>
        <hr />
        <br />
        <el-input v-model="manSearchKey"
                  placeholder="请输入人员姓名搜索"
                  class="search-input"
                  clearable>
            <template #prefix>
                <el-icon class="el-input__icon"><Search /></el-icon>
            </template>
        </el-input>
        <br />
        <h3>所属部门：{{ selectedOrgName || '未选择部门' }}</h3>
        <el-select v-model="selectedMan"
                   placeholder="请选择人员"
                   style="width: 100%"
                   v-on:change="confirmMan">
            <el-option v-for="man in searchFilteredManData"
                       :key="man.usersId"
                       :label="man.usersTrueName"
                       :value="man.usersId">
            </el-option>
        </el-select>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="salesManVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="confirmMan">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 货品选择模态框 -->
    <el-dialog v-model="goodsModalVisible" title="选择销售货品">
        <div style="margin-bottom: 15px;">
            <el-input v-model="goodsSearch" placeholder="搜索货品名称/编号" style="width: 300px;"></el-input>
            <el-button type="primary" v-on:click="searchGoods" style="margin-left: 10px;">搜索</el-button>
        </div>
        <el-table :data="filteredGoods" style="width: 100%" v-on:selection-change="handleGoodsSelection"
                  ref="goodsTable" stripe border>
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="goodsName" label="货品名称" width="180"></el-table-column>
            <el-table-column prop="goodsCode" label="货品编号" width="150"></el-table-column>
            <el-table-column prop="specification" label="规格型号" width="150"></el-table-column>
            <el-table-column prop="goodsTypeName" label="货品类型" width="120"></el-table-column>
            <el-table-column prop="currentStock" label="当前库存" width="120" align="right">
                <template #default="scope">
                    <span :class="{'stock-warning': scope.row.currentStock < 10, 'stock-error': scope.row.currentStock === 0}">
                        {{ scope.row.currentStock }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="salesReferencePrice" label="参考售价" width="120" align="right"></el-table-column>
        </el-table>
        <template #footer>
            <span class="dialog-footer">
                <el-button v-on:click="goodsModalVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="confirmGoodsSelection">确认添加</el-button>
            </span>
        </template>
    </el-dialog>
</div>

<script>
    const { createApp, ref, onMounted, computed, reactive } = Vue;
    const { ElMessage, ElMessageBox, ElIcon, Search, Document } = ElementPlus;

    // 详情页 script 开头添加（与管理页保持一致）
    const STATUS_CONFIG = {
            '0': { text: '草稿', class: 'status-draft' },
            '1': { text: '待审核', class: 'status-pending' },
            '2': { text: '驳回', class: 'status-rejected' },
            '3': { text: '未入库', class: '' },
            '4': { text: '部分入库', class: '' },
            '5': { text: '已完成', class: 'status-approved' },
            '6': { text: '已关闭', class: 'status-closed' }
    };

    const app = createApp({
        components: {
            ElIcon,
            Search,
            Document
        },
        setup() {
            // 创建表单
            const form = ref({
                salesOrderId: 0,
                salesOrderNo: '',
                salesDate: new Date().toISOString().split('T')[0],
                customerId: '',
                customerName: '',
                customerContact: '',
                customerPhone: '',
                salesDept: '',
                sellerBy: '',
                orderStatus: '1',
                auditorBy: 0,
                auditorTime: '',
                auditorComment: '',
                isDelete: '0',
                createBy: 'admin',
                createTime: new Date(),
                updateBy: 'admin',
                updateTime: new Date(),
                remarks: ''
            });

            // 2. 新增状态文本计算属性（用于页面显示，可选）
            const orderStatusText = computed(() => {
                return STATUS_CONFIG[form.value.orderStatus]?.text || '待审核';
            });

            // 新增：获取状态样式的方法（与管理页一致）
            const getStatusClass = (status) => {
                return STATUS_CONFIG[status]?.class || '';
            };

            // 修复批次号生成逻辑
            const addBatch = () => {
                const batchNum = batchList.value.length + 1;
                batchList.value.push({
                    quantity: 0,
                    batchNo: `BATCH${batchNum}`, // 修复字符串模板
                    productionDate: ''
                });
            };

            // 修复批次确认逻辑
            const confirmBatchManagement = () => {
                if (currentInventoryRow.value) {
                    // 更新期初库存为批次总数
                    currentInventoryRow.value.initialStock = calculateTotalQuantity.value;
                    currentInventoryRow.value.initialStockBatches = [...batchList.value];

                    // 重新计算期初金额
                    if (isInitialStockEnabled.value && form.salesReferencePrice >= 0) {
                        currentInventoryRow.value.initialAmount = calculateTotalQuantity.value * Number(form.salesReferencePrice);
                    }
                }
                batchManagementVisible.value = false;
            };

            // 从进货页面提取的部门和人员选择功能
            const salesDepartVisible = ref(false);
            const salesManVisible = ref(false);
            const goodsModalVisible = ref(false);

            const selectedDepart = ref('');
            const selectedMan = ref('');
            const selectedManName = ref('');
            const currentDepart = ref(null);
            const selectedOrgName = ref('');
            const selectedDepartOrgId = ref(null);
            const flatDepartList = ref([]);
            const filteredManData = ref([]);
            const selectedManId = ref('');

            // 搜索关键词
            const departSearchKey = ref('');
            const manSearchKey = ref('');
            const goodsSearch = ref('');

            // 部门数据
            const departData = ref([]);
            const defaultProps = ref({
                children: 'children',
                label: 'label'
            });

            // 人员数据
            const manData = ref([]);

            // 销售明细相关
            const salesDetails = ref([]);
            const selectedDetails = ref([]);
            const goodsList = ref([]);
            const selectedGoods = ref([]);

            // 附件相关
            const fileInput = ref(null);
            const uploadedFiles = ref([]);

            // 客户选项
            const customerOptions = ref([]);

            // 计算属性
            const totalQuantity = computed(() => {
                return salesDetails.value.reduce((sum, item) => sum + (Number(item.orderQuantity) || 0), 0);
            });

            const totalAmount = computed(() => {
                return salesDetails.value.reduce((sum, item) => sum + (Number(item.salesAmount) || 0), 0);
            });

            const filteredGoods = computed(() => {
                if (!goodsSearch.value) return goodsList.value;
                const searchVal = goodsSearch.value.toLowerCase();
                return goodsList.value.filter(goods =>
                    goods.goodsName?.toLowerCase().includes(searchVal) ||
                    goods.goodsCode?.toLowerCase().includes(searchVal)
                );
            });

            // 计算属性：部门搜索过滤
            const filteredDepartData = computed(() => {
                if (!departSearchKey.value) return departData.value;
                const keyword = departSearchKey.value.toLowerCase();

                const filterTree = (nodes) => {
                    return nodes
                        .filter(node => {
                            const matchSelf = node.name?.toLowerCase().includes(keyword) ||
                                            node.label?.toLowerCase().includes(keyword);
                            const filteredChildren = filterTree(node.children || []);
                            return matchSelf || filteredChildren.length > 0;
                        })
                        .map(node => ({
                            ...node,
                            children: filterTree(node.children || [])
                        }));
                };

                return filterTree(departData.value);
            });

            // 计算属性：人员搜索过滤
            const searchFilteredManData = computed(() => {
                if (!manSearchKey.value) return filteredManData.value;
                const keyword = manSearchKey.value.toLowerCase();
                return filteredManData.value.filter(man => {
                    return man.usersTrueName?.toLowerCase().includes(keyword);
                });
            });

            // 数字格式化函数（修复 toFixed 错误）
            const formatNumber = (value) => {
                if (value === null || value === undefined || isNaN(Number(value))) {
                    return '0.00';
                }
                return Number(value).toFixed(2);
            };

            // 部门节点点击
            const departNode = (data) => {
                currentDepart.value = data;
                selectedDepartOrgId.value = data.id;
                departData.value.forEach(node => {
                    node.highlight = node.id === data.id;
                });
            };

            // 确认部门选择
            const confirmDepart = () => {
                if (currentDepart.value) {
                    selectedDepart.value = currentDepart.value.label;
                    selectedDepartOrgId.value = currentDepart.value.id;
                    selectedOrgName.value = currentDepart.value.label;

                    // 更新表单中的销售部门
                    form.value.salesDept = currentDepart.value.id;

                    // 过滤该部门下的人员
                    filteredManData.value = manData.value.filter(man => {
                        return man && String(man.orgId) === String(selectedDepartOrgId.value);
                    });
                    selectedMan.value = '';
                    selectedManName.value = '';
                } else {
                    selectedDepart.value = '';
                    selectedDepartOrgId.value = null;
                    selectedOrgName.value = '';
                    filteredManData.value = manData.value;
                    //ElMessage.info('未选择部门，将显示所有人员');
                }
                salesDepartVisible.value = false;
            };

            // 打开人员模态框
            const openManModal = () => {
                selectedOrgName.value = selectedDepart.value || '';
                salesManVisible.value = true;
            };
            // 确认人员选择
            const confirmMan = () => {
                if (selectedMan.value) {
                    const selectedManObj = manData.value.find(man => {
                        return man && man.usersId && String(man.usersId) === String(selectedMan.value);
                    });

                    if (!selectedManObj) {
                       // ElMessage.error('未找到匹配的人员，请刷新页面重试');
                        salesManVisible.value = false;
                        return;
                    }
                    selectedManId.value = selectedMan.value;
                    const manOrgId = selectedManObj.orgId;
                    if (!manOrgId) {
                       // ElMessage.error('人员部门信息异常');
                        salesManVisible.value = false;
                        return;
                    }

                    const matchedDepart = flatDepartList.value.find(depart => {
                        return depart && depart.orgId && String(depart.orgId) === String(manOrgId);
                    });

                    if (matchedDepart) {
                        selectedDepart.value = matchedDepart.label;
                        selectedOrgName.value = matchedDepart.label;
                        selectedDepartOrgId.value = manOrgId;

                        // 更新表单中的销售部门和负责人
                        form.value.salesDept = manOrgId;
                        form.value.sellerBy = selectedManId.value;

                        filteredManData.value = manData.value.filter(man =>
                            man && man.orgId && String(man.orgId) === String(manOrgId)
                        );
                        selectedManName.value = selectedManObj.usersTrueName;
                    } else {
                       // ElMessage.error('未找到匹配的部门，请刷新页面重试');
                    }

                    salesManVisible.value = false;
                } else {
                  //  ElMessage.warning('请选择人员');
                }
            };

            // 加载部门数据
            const loadDepartData = async () => {
                try {
                    const departRes = await axios.get('/StockUpOrder/GetOrgInfoForSelectTable');
                    departData.value = Array.isArray(departRes.data) ? departRes.data : [];
                    if (departData.value.length === 0) {
                       // ElMessage.warning('部门数据为空，请检查接口');
                    }

                    const flattenDepart = (departArray) => {
                        let result = [];
                        departArray.forEach(depart => {
                            if (!depart) return;
                            const flatDepart = {
                                orgId: depart.id || depart.orgId,
                                label: depart.name || depart.label,
                                children: Array.isArray(depart.children) ? depart.children : []
                            };
                            result.push(flatDepart);
                            if (flatDepart.children.length > 0) {
                                result = [...result, ...flattenDepart(flatDepart.children)];
                            }
                        });
                        return result;
                    };
                    flatDepartList.value = flattenDepart(departData.value);
                } catch (err) {
                  //  console.error('获取部门数据失败：', err);
                    departData.value = [];
                    flatDepartList.value = [];
                }
            };

            // 加载人员数据
            const loadManData = async () => {
                try {
                    const manRes = await axios.get('/StockUpOrder/GetUserInfoForSelectTable');
                    manData.value = (manRes.data || []).filter(man => man && man.usersId);
                    filteredManData.value = manData.value;
                    if (manData.value.length === 0) {
                       // ElMessage.warning('未加载到有效人员数据');
                    }
                } catch (err) {
                   // console.error('获取人员数据失败：', err);
                    manData.value = [];
                    filteredManData.value = [];
                }
            };

            // 客户选择变更
            const handleCustomerChange = (customerId) => {
                const customer = customerOptions.value.find(item => item.id === customerId);
                if (customer) {
                    form.value.customerName = customer.name;
                    form.value.customerContact = customer.contactPerson;
                    form.value.customerPhone = customer.contactPhone;
                }
            };

            // 货品选择相关
            const openGoodsSelectModal = () => {
                goodsModalVisible.value = true;
            };

            const handleGoodsSelection = (val) => {
                selectedGoods.value = val;
            };

            const searchGoods = () => {};

            const checkInventory = async (goodsCode, requiredQuantity) => {
                try {
                    const response = await axios.post(`/OmSalesOrder/GetInventoryByGoodsCode?goodsCode=${goodsCode}`);
                    if (response.data.code === 200) {
                        const inventoryList = response.data.data;
                        const totalStock = inventoryList.reduce((sum, item) => sum + (Number(item.availableInventoryQty) || 0), 0);
                        return {
                            success: totalStock >= requiredQuantity,
                            totalStock: totalStock,
                            inventoryList: inventoryList
                        };
                    }
                    return { success: false, totalStock: 0, inventoryList: [] };
                } catch (error) {
                    console.error('检查库存失败:', error);
                    return { success: false, totalStock: 0, inventoryList: [] };
                }
            };

            // 处理货品数量输入
            const handleQuantityInput = (row, event) => {
                // 过滤非数字字符
                let value = event.target.value.replace(/[^\d]/g, '');

                // 如果输入为空，设置为1
                if (value === '') {
                    value = '1';
                }

                // 限制最大值为当前库存
                const maxValue = row.currentStock;
                if (Number(value) > maxValue) {
                    value = maxValue.toString();
                }

                // 更新值
                row.orderQuantity = Number(value);
                calculateAmount(row);

                // 更新输入框显示值
                event.target.value = value;
            };

            // 验证货品数量
            const validateQuantity = (row) => {
                // 确保数量为有效数字
                if (isNaN(row.orderQuantity) || row.orderQuantity <= 0) {
                    row.orderQuantity = 1;
                }

                // 确保不超过库存
                if (row.orderQuantity > row.currentStock) {
                    row.orderQuantity = row.currentStock;
                    ElMessage.warning(`货品「${row.goodsName}」数量已调整为最大可用库存 ${row.currentStock}`);
                }

                calculateAmount(row);
            };

            // 修改货品选择确认方法
            const confirmGoodsSelection = async () => {
                if (selectedGoods.value.length === 0) {
                  //  ElMessage.warning('请至少选择一个货品');
                    return;
                }

                const existingCodes = salesDetails.value.map(item => item.goodsCode);
                const newGoods = selectedGoods.value.filter(goods => !existingCodes.includes(goods.goodsCode));

                for (const goods of newGoods) {
                    // 检查库存是否足够（无批次版本）
                    const inventoryCheck = await checkInventory(goods.goodsCode, 1);

                    if (!inventoryCheck.success) {
                     //   ElMessage.warning(`货品「${goods.goodsName}」库存不足，当前总库存仅${inventoryCheck.totalStock}`);
                        continue;
                    }

                    salesDetails.value.push({
                        salesDetailId: 0,
                        salesOrderId: 0,
                        goodsCode: goods.goodsCode,
                        goodsName: goods.goodsName,
                        specification: goods.specification,
                        goodsType: goods.goodsTypeName,
                        goodsTypeId: goods.goodsId,
                        currentStock: inventoryCheck.totalStock, // 使用实际库存数量
                        unit: goods.unit || '个',
                        orderQuantity: 1,
                        salesUnitPrice: goods.salesReferencePrice || 0,
                        salesAmount: (goods.salesReferencePrice || 0) * 1,
                        outboundQty: 0,
                        unshippedQty: 1,
                        isDelete: '0',
                        attachmentId: 0,
                        remarks: ''
                    });
                }

                if (newGoods.length > 0) {
                //    ElMessage.success(`成功添加${newGoods.length}个货品`);
                }

                goodsModalVisible.value = false;
                selectedGoods.value = [];
            };


            // 计算销售金额
            const calculateAmount = (row) => {
                const quantity = Number(row.orderQuantity) || 0;
                const price = Number(row.salesUnitPrice) || 0;
                row.salesAmount = quantity * price;
                row.unshippedQty = quantity;
            };

            // 明细操作
            const handleDetailSelection = (val) => {
                selectedDetails.value = val;
            };

            const removeDetail = (row) => {
                salesDetails.value = salesDetails.value.filter(item => item.goodsCode !== row.goodsCode);
            //    ElMessage.success('已移除该货品明细');
            };

            const removeSelectedDetails = () => {
                if (selectedDetails.value.length === 0) {
                 //   ElMessage.warning('请先勾选要移除的明细');
                    return;
                }

                const codes = selectedDetails.value.map(item => item.goodsCode);
                salesDetails.value = salesDetails.value.filter(item => !codes.includes(item.goodsCode));
               // ElMessage.success(`已移除${selectedDetails.value.length}条明细`);
                selectedDetails.value = [];
            };

            // 附件上传处理
            const triggerFileInput = () => {
                fileInput.value.click();
            };

            const handleFileUpload = (event) => {
                const files = event.target.files;
                if (!files || files.length === 0) return;

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    uploadedFiles.value.push({
                        file: file,
                        name: file.name
                    });
                }

               // ElMessage.success(`已添加 ${files.length} 个附件到本地`);
                event.target.value = '';
            };

            const removeFile = (index) => {
                uploadedFiles.value.splice(index, 1);
              //  ElMessage.info('文件已删除');
            };

            // 获取当前用户ID
            const getCurrentUserId = () => {
                const userStr = sessionStorage.getItem('YH');
                if (!userStr) {
               //     ElMessage.warning('未检测到登录状态，请重新登录');
                    return '';
                }
                try {
                    const userObj = JSON.parse(userStr);
                    const userId = userObj?.id?.toString() || '';
                    if (!userId) {
                      //  ElMessage.warning('用户信息不完整，请重新登录');
                    }
                    return userId;
                } catch (error) {
               //     console.error('解析用户信息失败：', error);
                    return '';
                }
            };
            // 1. 新增：从URL获取订单ID（编辑场景）
            const getOrderIdFromUrl = () => {
                const urlParams = new URLSearchParams(window.location.search);
                return urlParams.get('id');
            };

            // 2. 新增：加载编辑数据
            const loadEditData = async (orderId) => {
                try {
                    const response = await axios.post(`/OmSalesOrder/Details?id=${orderId}`);
                    if (response.data.code === 200) {
                        const orderData = response.data.data[0];
                        // 状态回显（直接接收数字字符串，与管理页一致）
                        form.value.orderStatus = orderData.orderStatus || '1';
                    }
                } catch (error) {
                  //  console.error('加载编辑数据失败:', error);
                }
            };

            // 3. 修改初始化逻辑：区分新增/编辑场景
            const loadData = async () => {
                try {
                    await loadDepartData();
                    await loadManData();
                    const currentUserId = getCurrentUserId();
                    form.value.createBy = currentUserId;
                    form.value.updateBy = currentUserId;

                    // 生成销售单号（新增场景）
                    const orderId = getOrderIdFromUrl();
                    if (!orderId) {
                        await generateOrderNo();
                    } else {
                        // 编辑场景：加载已有数据（含状态）
                        await loadEditData(orderId);
                    }

                    // 加载客户列表、货品列表（原有逻辑不变）
                    const customerRes = await axios.post('/OmSalesOrder/CustomerAll');
                    if (customerRes.data.code === 200) {
                        customerOptions.value = customerRes.data.data;
                    }
                    const goodsRes = await axios.post('/BiProduct/GetAll');
                    if (goodsRes.data.code === 200) {
                        goodsList.value = goodsRes.data.data.result;
                    }
                } catch (error) {
                //    ElMessage.error('数据加载失败，请刷新重试');
                    console.error(error);
                }
            };
            // 表单验证
            const validateForm = () => {
                if (!form.value.salesDate) {
                    ElMessage.error('请选择销售日期');
                    return false;
                }
                if (!form.value.customerId) {
                    ElMessage.error('请选择客户名称');
                    return false;
                }
                if (!form.value.sellerBy) {
                    ElMessage.error('请选择销售负责人');
                    return false;
                }
                if (salesDetails.value.length === 0) {
                    ElMessage.error('请至少添加一条销售货品明细');
                    return false;
                }

                // 详细验证明细数据
                for (let i = 0; i < salesDetails.value.length; i++) {
                    const item = salesDetails.value[i];
                    if (!item.unit) {
                        ElMessage.error(`第${i + 1}行货品请选择单位`);
                        return false;
                    }
                    if (!item.orderQuantity || item.orderQuantity <= 0) {
                        ElMessage.error(`第${i + 1}行货品数量必须大于0`);
                        return false;
                    }
                    if (!item.salesUnitPrice || item.salesUnitPrice <= 0) {
                        ElMessage.error(`第${i + 1}行货品单价必须大于0`);
                        return false;
                    }
                    if (item.orderQuantity > item.currentStock) {
                        ElMessage.error(`第${i + 1}行货品「${item.goodsName}」库存不足，当前库存${item.currentStock}`);
                        return false;
                    }
                }
                return true;
            };

           // 提交相关
            const submitForm = async (isAddNew = false) => {
                // 使用新的验证方法
                const isValid = await validateForm();
                if (!isValid) return;

                try {
                    if (salesDetails.value.length === 0) {
                        ElMessage.error('请至少添加一条销售货品明细');
                        return;
                    }

                    // 构建提交数据 - 保持明细分开，不合并
                    const submitData = {
                        salesOrder: {
                            salesOrderNo: form.value.salesOrderNo,
                            customerId: form.value.customerId,
                            sellerBy: form.value.sellerBy,
                            salesDate: form.value.salesDate,
                            orderStatus: form.value.orderStatus,
                            remarks: form.value.remarks,
                            isDelete: form.value.isDelete,
                            createBy: form.value.createBy,
                            createTime: new Date().toISOString(),
                            updateBy: form.value.updateBy,
                            updateTime: new Date().toISOString()
                        },
                        salesOrderDetails: salesDetails.value.map(detail => ({
                            goodsCode: detail.goodsCode,
                            goodsTypeId: detail.goodsTypeId,
                            salesUnitPrice: detail.salesUnitPrice,
                            salesAmount: detail.salesAmount,
                            orderQuantity: detail.orderQuantity,
                            outboundQty: detail.outboundQty || 0,
                            unshippedQty: detail.unshippedQty || detail.orderQuantity,
                            isDelete: detail.isDelete || '0',
                            remarks: detail.remarks || '',
                            attachmentId: 0
                        }))
                    };

                    const response = await axios.post("/OmSalesOrder/Create", submitData);
                    if (response.data.code === 200) {
                        ElMessage.success('销售订单提交成功！');
                        if (isAddNew) {
                            resetForm();
                        } else {
                            closePage();
                        }
                    } else {
                        ElMessage.error('提交失败: ' + response.data.msg);
                    }
                } catch (error) {
                    console.error('提交错误:', error);
                }
            };

            const saveDraft = async () => {
                form.value.orderStatus = '0'; // 草稿对应数字0
                await submitForm(false);
            };

            const saveAndAdd = async () => {
                form.value.orderStatus = '1'; // 待审核对应数字1
                await submitForm(true);
            };
            const closePage = () => {
                window.history.back();
            };
            // 重置表单函数
            const resetForm = () => {
                form.value = {
                    salesOrderId: 0,
                    salesOrderNo: '',
                    salesDate: new Date().toISOString().split('T')[0],
                    customerId: '',
                    customerName: '',
                    customerContact: '',
                    customerPhone: '',
                    salesDept: '',
                    sellerBy: '',
                    orderStatus: '1',
                    auditorBy: 0,
                    auditorTime: '',
                    auditorComment: '',
                    isDelete: '0',
                    createBy: getCurrentUserId(),
                    createTime: new Date(),
                    updateBy: getCurrentUserId(),
                    updateTime: new Date(),
                    remarks: ''
                };
                salesDetails.value = [];
                uploadedFiles.value = [];
                selectedDepart.value = '';
                selectedManName.value = '';
                selectedMan.value = '';

                // 重新生成单号
                generateOrderNo();
            };

            // 生成订单号函数
            const generateOrderNo = async () => {
                try {
                    const orderNoRes = await axios.post('/NumberingRules/GenerateByRuleId?ruleId=8');
                    if (orderNoRes.data && orderNoRes.data.success) {
                        form.value.salesOrderNo = orderNoRes.data.number;
                    }
                } catch (error) {
                    console.error('生成销售单号失败：', error);
                }
            };

            // 初始化加载
            onMounted(() => {
                loadData();
            });

            return {
                form,
                salesDetails,
                selectedDetails,
                totalQuantity,
                totalAmount,
                customerOptions,
                goodsList,
                goodsModalVisible,
                goodsSearch,
                filteredGoods,
                handleCustomerChange,
                openGoodsSelectModal,
                handleGoodsSelection,
                searchGoods,
                confirmGoodsSelection,
                calculateAmount,
                handleDetailSelection,
                removeDetail,
                removeSelectedDetails,
                fileInput,
                uploadedFiles,
                triggerFileInput,
                handleFileUpload,
                removeFile,
                submitForm,
                saveDraft,
                saveAndAdd,
                closePage,
                formatNumber,
                handleQuantityInput,
                validateQuantity,
                salesDepartVisible,
                salesManVisible,
                selectedDepart,
                selectedMan,
                selectedManName,
                departData,
                manData,
                defaultProps,
                departNode,
                confirmDepart,
                confirmMan,
                openManModal,
                selectedOrgName,
                departSearchKey,
                manSearchKey,
                filteredDepartData,
                searchFilteredManData
            };
        }
    });

    app.use(ElementPlus);
    app.mount('#app');
</script>
<style>
    /* 保留原有样式并恢复附件相关样式 */
    .custom-active-action, .custom-inactive-action {
        color: red;
        font-size: 12px;
        font-weight: bold;
        width: 100%;
        text-align: center;
    }

    .el-switch__action {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .basicInfo, .stockInfo, .uploadAttachment {
        width: 82%;
        background-color: #fff;
        padding: 20px 0 10px;
        box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        margin: 20px;
    }

    .stockInfo, .uploadAttachment {
        padding-top: 10px;
        min-height: 400px;
    }

    .saveBlock {
        display: grid;
        place-items: center;
        position: sticky;
        bottom: 0;
        width: 100%;
        height: 60px;
        background-color: #fff;
        z-index: 20;
        box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        margin: 20px;
    }

    .titleH {
        margin-left: 40px;
    }

    .form-row {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -10px;
    }

    .form-col {
        flex: 0 0 50%;
        padding: 0 10px;
        box-sizing: border-box;
    }

    .full-width {
        flex: 0 0 100%;
    }

    .form-container {
        padding: 0 40px;
    }

    .required-label::before {
        content: '*';
        color: #F56C6C;
        margin-right: 4px;
    }

    .stockTable {
        margin: 20px 40px;
        width: 95%;
        overflow-x: auto;
    }

        .stockTable .el-table {
            width: 100%;
            min-width: 1200px;
            table-layout: fixed;
        }

            .stockTable .el-table th {
                background-color: #f5f7fa;
                text-align: center;
            }

            .stockTable .el-table td {
                text-align: center;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

    .add-remove-buttons {
        margin: 10px 40px;
    }

    .total-summary {
        text-align: right;
        margin: 10px 40px;
        font-size: 16px;
        font-weight: bold;
        color: #303133;
    }

    /* 恢复附件上传样式 */
    .uploadAttach {
        padding-top: 30px;
        padding-left: 60px;
    }

    .promptWord {
        color: #606266;
    }

    .attachment-list {
        margin-top: 20px;
    }

    .attachment-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        border: 1px solid #e5e7eb;
        border-radius: 4px;
        margin-bottom: 8px;
    }

    .attachment-info {
        display: flex;
        align-items: center;
    }

    .attachment-icon {
        margin-right: 8px;
        color: #409EFF;
    }

    /* 部门和人员选择模态框样式 */
    .tree-container {
        max-height: 400px;
        overflow-y: auto;
    }

    .search-input {
        margin-bottom: 15px;
    }

    .dialog-footer {
        text-align: right;
        padding: 10px 0;
    }

    /* 只读输入框样式 */
    .custom-readonly-input .el-input__inner {
        background-color: #f0f0f0 !important;
        cursor: pointer;
    }

    .custom-readonly-input .el-input__wrapper {
        background-color: #f0f0f0 !important;
    }

    /* 树控件样式优化 */
    .el-tree {
        border: 1px solid #e5e7eb;
        border-radius: 4px;
        padding: 10px;
    }

    .tree-title {
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
    }

    /* 新增样式：数量输入限制提示 */
    .quantity-input-hint {
        font-size: 12px;
        color: #909399;
        margin-top: 4px;
    }

    .quantity-input-error {
        font-size: 12px;
        color: #f56c6c;
        margin-top: 4px;
    }

    .stock-warning {
        color: #e6a23c;
    }

    .stock-error {
        color: #f56c6c;
    }

    .orderTable {
        margin: 0 auto;
        width: 80%;
        border-spacing: 0 50px; /* 增加垂直间距 */
    }

    .imp {
        color: red;
    }

    .orderTable tbody tr td {
        border-spacing: 0 25px; /* 增加单元格间距 */
        padding: 12px 0; /* 增加上下内边距 */
        vertical-align: top; /* 顶部对齐 */
    }

    .custom-readonly-input .el-input__inner {
        background-color: #f0f0f0 !important;
        padding: 0px;
    }

    .custom-readonly-input .el-input__wrapper {
        background-color: #f0f0f0 !important;
    }

    .related-order-input-group {
        display: flex;
        align-items: center;
    }

    /* 为表格行添加更好的视觉分隔 */
    .orderTable tbody tr {
        height: 70px; /* 设置固定行高 */
    }

        /* 为备注行特殊处理 */
        .orderTable tbody tr:last-child td {
            padding-top: 20px; /* 备注行额外上边距 */
            padding-bottom: 20px; /* 备注行额外下边距 */
        }

    /* 调整表单元素间距 */
    .orderTable .el-input,
    .orderTable .el-select,
    .orderTable .el-cascader,
    .orderTable .el-date-picker {
        margin-bottom: 8px; /* 表单元素底部间距 */
    }

    /* 调整复选框位置 */
    .orderTable .el-checkbox {
        margin-top: 8px;
    }

    /* 调整文本域高度 */
    .orderTable .el-textarea .el-textarea__inner {
        min-height: 80px; /* 增加备注文本域高度 */
        resize: vertical; /* 允许垂直调整 */
    }

    /* 在 style 中添加 */
    .orderTable .el-date-picker {
        width: 160px !important; /* 强制固定宽度 */
        box-sizing: border-box; /* 确保内边距不影响总宽度 */
    }
</style>
